import os
import time
import tkinter as tk
from tkinter import messagebox
import requests
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import pandas as pd
import yaml

limit_upload_counter = 0


class CSVFileHandler(FileSystemEventHandler):
    def __init__(self, config, root):
        self.config = config
        self.CSV_DIR = config['directories']['csv_dir']
        self.processed_files = set()
        self.backend_url = 'http://192.168.16.4:8000/animoor-smt/AoiCheck/checkBarCode'
        self.root = root

    def on_modified(self, event):
        global limit_upload_counter
        print(limit_upload_counter)
        if not event.is_directory and event.src_path.endswith('.CSV'):
            if limit_upload_counter >= 1:
                limit_upload_counter = 0
                print(limit_upload_counter)
                return
            else:
                limit_upload_counter += 1
                print(limit_upload_counter)
                print(f'文件 {event.src_path} 发生变化.')
                time.sleep(0.5)
                self.parse_and_insert_csv(event.src_path)

    def parse_and_insert_csv(self, file_path):
        try:
            df = pd.read_csv(file_path, encoding='GB2312', header=None, names=range(31))
            part1 = df.iloc[1, 5]
            print(part1)  # 获取二维码号
            if not str(part1).startswith('F'):
                print("二维码号不是以F开头，跳过后续处理。")
                return  # 如果不是以F开头，则退出函数
            part2 = df.iloc[3:, 11].fillna("").tolist()
            if not part2:
                status = 0
                self.send_data_to_backend(part1, status)  # 说明不存在NG
            else:
                if "NG" in part2:
                    status = 1
                    self.send_data_to_backend(part1, status)  # 说明存在NG
                else:
                    status = 0
                    self.send_data_to_backend(part1, status)  # 说明不存在NG
        except Exception as e:
            print(f'Error : {e}')

    def send_data_to_backend(self, part1, status):
        """发送数据到后端"""
        url = self.backend_url
        headers = {'Content-Type': 'application/json'}
        payload = {
            'productCode': part1,
            'status': status
        }  # 构造要发送的数据
        response = requests.post(url, json=payload, headers=headers)
        if response.status_code == 200:
            try:
                data = response.json()  # 如果后端返回的是JSON格式的数据
                print(f"后端返回的数据: {data}")
                # 处理具体的响应数据
                if data['code'] == 4004 and (data['msg'] == '请求资源不存在: 该二维码不存在，请补码' or data['msg'] == '请求资源不存在: 该板卡存在二维码缺失，请补码'):
                    self.show_popup(data['msg'])
                else:
                    print(f"后端返回成功消息: {data['msg']}")
            except ValueError:  # 如果不是JSON格式的数据，捕获异常
                print(f"后端返回的非JSON数据: {response.text}")
        else:
            print(f"发送数据失败，状态码: {response.status_code}, 响应内容: {response.text}")

    def show_popup(self, message):
        # 创建一个新的顶级窗口
        popup = tk.Toplevel(self.root)
        popup.title("提示")
        popup.geometry("300x150")  # 设置窗口大小
        popup.attributes('-topmost', True)  # 设置窗口始终置顶

        # 添加一个标签显示消息
        label = tk.Label(popup, text=message, padx=20, pady=20)
        label.pack()

        # 添加一个关闭按钮
        close_button = tk.Button(popup, text="确定", command=popup.destroy)
        close_button.pack(pady=10)

        # 确保窗口在屏幕上居中
        popup.update_idletasks()
        width = popup.winfo_width()
        height = popup.winfo_height()
        x = (popup.winfo_screenwidth() // 2) - (width // 2)
        y = (popup.winfo_screenheight() // 2) - (height // 2)
        popup.geometry(f'{width}x{height}+{x}+{y}')

        # 使弹窗成为焦点
        popup.grab_set()
        popup.focus_set()
        popup.wait_window()


if __name__ == "__main__":
    with open('config.yml', 'r') as file:
        config = yaml.safe_load(file)

    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口

    event_handler = CSVFileHandler(config, root)
    observer = Observer()
    observer.schedule(event_handler, config['directories']['csv_dir'], recursive=False)
    observer.start()
    print(f'Starting to monitor {config["directories"]["csv_dir"]}...')

    try:
        root.mainloop()  # 启动 Tkinter 主事件循环
    except KeyboardInterrupt:
        observer.stop()
    observer.join()